package viu

import (
	"github.com/gocolly/colly"
	"github.com/gogf/gf/v2/encoding/gjson"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/gogf/gf/v2/text/gregex"
	"github.com/gogf/gf/v2/util/gconv"
	"time"
	"uni-crawl-frame/core"
	"uni-crawl-frame/db/mysql/model/entity"
	"uni-crawl-frame/service/crawl/replayservice"
)

type ViuTvCrawl struct {
	*core.AbstractCrawlReplayUrl
}

func (receiver *ViuTvCrawl) CreateProgram(replayConfig *entity.CmsCrawlReplayConfig, manifestTask *entity.CmsCrawlReplayManifestTask) {
	log := g.Log().Line()

	matchResults, _ := gregex.MatchString(".*/epgs/(.*)", replayConfig.SeedUrl)
	log.Infof(gctx.GetInitCtx(),
		"viu tv电视台NO. = %s", matchResults[1])

	coll := colly.NewCollector()

	coll.OnResponse(func(response *colly.Response) {
		jsonArray := gjson.New(response.Body).Get("epgs").Array()
		for _, jsonItem := range jsonArray {
			json := gjson.New(jsonItem)

			title := json.Get("program_title").String()

			start := json.Get("start").String()
			startTimestamp := gconv.Int(start)
			programStartTime := time.Unix(int64(startTimestamp/1000), 0)

			end := json.Get("end").String()
			endTimestamp := gconv.Int(end)
			programEndTime := time.Unix(int64(endTimestamp/1000), 0)

			log.Infof(gctx.GetInitCtx(),
				"节目 = %s. start at %s", title, programStartTime)

			programTask := new(entity.CmsCrawlReplayProgramTask)
			programTask.ManifestId = manifestTask.Id
			programTask.ConfigId = replayConfig.Id
			programTask.ProgramName = title
			programTask.CrawlStatus = replayservice.ProgramTaskInit

			programTask.ProgramStartTime = gtime.NewFromTime(programStartTime)
			programTask.ProgramEndTime = gtime.NewFromTime(programEndTime)
			programTask.ProgramNo = programTask.ProgramStartTime.TimestampMilliStr()
			programTask.HostIp = replayConfig.Host
			programTask.CreateTime = gtime.Now()

			replayservice.CheckAndSave(programTask)
		}

	})

	_ = coll.Visit(replayConfig.SeedUrl)

}
